package com.lzy.system.organization.handler;

import com.lzy.system.organization.entity.SysUser;
import com.lzy.system.organization.entity.security.entity.SecurityUser;
import com.lzy.system.organization.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    ISysUserService iSysUserService;
    //supportsParameter 指定当参数类型为 User 类时才应用该参数解析器
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(SysUser.class);
    }

    //自定义的参数解析逻辑，例如创建一个 User 对象并返回
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser)authentication.getPrincipal();
        SysUser user = iSysUserService.getUserById(securityUser.getId());
        return user;
    }
}
